const Sequelize = require('sequelize')
const sequelize = require('../db/dbconfig')
const TabsModel = require('../db/models/tabs')
const {deleteProjectCate} = require("./projectCate");
const url = require("url");
const fs = require("querystring");
const tabsModel = TabsModel(sequelize)
const Op = Sequelize.Op

// 增
exports.addTab = async (req, res) => {
  try {
    const tab = req.body
    let is_exist = await tabsModel.findOne({
      where: {
        is_delete: 0,
        tab_name: tab.tab_name
      }
    })
    if(is_exist !== null) return res.myMsg('添加失败，该标签已存在')
    let results = await tabsModel.create({
      tab_name: tab.tab_name
    })
    res.myMsg('标签添加成功',0)
  }catch (e) {
    res.myMsg(e)
  }
}
// 删
exports.delTab = async (req, res) => {
  try {
    let results = await tabsModel.update({
      is_delete: 1
    },{
      where: {
        tab_id: req.params.id
      }
    })
    if(results[0] === 0) return res.myMsg('删除失败，标签不存在')
    res.myMsg('标签删除成功',0)
  } catch (e) {
    res.myMsg(e)
  }
}
// 改
exports.updateTab = async (req, res) => {
  try{
    const tab = req.body
    let is_exist = await tabsModel.findOne({
      where: {
        is_delete: 0,
        tab_id: tab.tab_id
      }
    })
    if(is_exist === null) return res.myMsg('修改失败，标签不存在')
    let results = await tabsModel.update({
      tab_name: tab.tab_name
    }, {
      where: {
        tab_id: tab.tab_id
      }
    })
    res.myMsg('标签修改成功',0)
  }catch (e) {
    res.myMsg(e)
  }
}
// 查
exports.getTabAll = async (req, res) => {
  try {
    // const {query} = url.parse(req.url, false);
    // let temp = parseInt(fs.parse(query).offset[0])
    // const offset = temp%2===0? temp:temp-1
    let results = await tabsModel.findAll({
      where: {
        is_delete: 0
      },
      order: [
          ['tab_id', 'asc']
      ]
    })
    res.myMsg(results, 0)
  }catch (e) {
    res.myMsg(e)
  }
}